package com.ysxsoft.wdg.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.classic.common.MultipleStatusView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.bean.response.LevelPayResponse;
import com.ysxsoft.wdg.bean.response.LevelResponse;
import com.ysxsoft.wdg.bean.response.WxResponse2;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.pay.PayPopWindow2;
import com.ysxsoft.wdg.pay.PayResultListener;
import com.ysxsoft.wdg.pay.PayUtils;
import com.ysxsoft.wdg.pay.WxPayBean;
import com.ysxsoft.wdg.ui.activity.my.LevelWebViewActivity;
import com.ysxsoft.wdg.util.JsonUtils;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.util.transform.FastSpeedLinearLayoutManager;
import com.ysxsoft.wdg.widget.alertview.AlertUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

public class LevelRechargeActivity extends BaseActivity{
    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.title_finish)
    ImageView titleFinish;
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.title_iv_r)
    ImageView titleIvR;
    @BindView(R.id.title_tv_r)
    TextView titleTvR;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.multStatusView)
    MultipleStatusView multStatusView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.parent)
    ConstraintLayout parent;
    @BindView(R.id.pay)
    Button pay;
    @BindView(R.id.btLayout)
    LinearLayout btLayout;
    private PayPopWindow2 payPopWindow;
    private MyAdapter adapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_level_recharge;
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, LevelRechargeActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initData() {
        initStatusBar(topView, false);
        titleContent.setText("立即升级");
        titleIvR.setImageResource(R.mipmap.question);
        titleIvR.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LevelRechargeActivity.this, LevelWebViewActivity.class);
                startActivity(intent);
            }
        });

        recyclerview.setNestedScrollingEnabled(false);
        recyclerview.setFocusable(false);
        recyclerview.setLayoutManager(new FastSpeedLinearLayoutManager(this));
        adapter = new MyAdapter(R.layout.item_level_recharge);
        recyclerview.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<LevelResponse.DataBean> list = adapter.getData();
                for (int i = 0; i < list.size(); i++) {
                    LevelResponse.DataBean d = list.get(i);
                    d.setSelected(i == position);
                    if (i == position) {
                        clickId = d.getId() + "";
                        clickMoney = d.getService();
                        money.setText("￥" + clickMoney);
                    }
                }
                adapter.notifyDataSetChanged();
            }
        });
        multStatusView.showLoading();
        getData();
    }

    private String clickId, clickMoney;

    @Override
    protected void setListener() {
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadmore(false);

    }

    @OnClick({R.id.title_finish, R.id.pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_finish:
                finish();
                break;
            case R.id.pay:
                showPayWindow(clickMoney, clickId);
                break;
        }
    }

    private void showPayWindow(String payMoney, String levelid) {
        if (payPopWindow != null) {
            payPopWindow.dismiss();
            payPopWindow = null;
        }
        payPopWindow = new PayPopWindow2(LevelRechargeActivity.this, payMoney);
        payPopWindow.show(parent);
        payPopWindow.setOnPayLiatener(new PayPopWindow2.OnPayLiatener() {
            @Override
            public void payType(int payType) {//payment= "3";
                AlertUtils.payAlert(LevelRechargeActivity.this);
                switch (payType) {
                    case 0://余额支付
//                        postPayYue();
                        pay("3", payMoney, levelid);
                        break;
                    case 1://支付宝支付
//                        postPayZfb();
                        pay("1", payMoney, levelid);
                        break;
                    case 2://微信支付
//                        ToastUtils.showToast("暂未开通");
//                        AlertUtils.dismissAlert();
                        pay("2", payMoney, levelid);
                        break;
                }
            }
        });
    }

    private void getData() {
        multStatusView.showLoading();
        OkHttpUtils.post()
                .url(UrlHost.LEVEL_PAGE)
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    multStatusView.showError();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                multStatusView.showContent();
                if (response != null) {
                    LevelResponse levelResponse = JsonUtils.parseByGson(response, LevelResponse.class);
                    if (levelResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(levelResponse.getCode())) {
                        List<LevelResponse.DataBean> dataBean = levelResponse.getData();
                        if (dataBean != null && dataBean.size() > 0) {
                            dataBean.get(0).setSelected(true);
                            clickId = dataBean.get(0).getId() + "";
                            clickMoney = dataBean.get(0).getService();
                            money.setText("￥" + clickMoney);
                        }
                        adapter.setNewData(dataBean);
                    } else {
                        ToastUtils.showToast(levelResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    /**
     * 支付订单
     */
    private void pay(String t, String account, String levelid) {
        OkHttpUtils.post()
                .url(UrlHost.LEVEL_PAY)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("type", t)//3余额2微信1支付宝
                .addParams("account", account)
                .addParams("levelid", levelid)//等级id
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                AlertUtils.dismissAlert();
                if (response != null) {
                    if ("2".equals(t)) {//微信支付
                        LevelPayResponse levelPayResponse = JsonUtils.parseByGson(response, LevelPayResponse.class);
                        if (levelPayResponse == null) {
                            return;
                        }
                        if (CallbackCode.SUCCESS.equals(levelPayResponse.getCode())) {
                            WxResponse2 response2 = JsonUtils.parseByGson(levelPayResponse.getData(), WxResponse2.class);
                            WxPayBean wxPayBean=new WxPayBean();
                            wxPayBean.setTimestamp(""+response2.getData().getTimestamp());
                            wxPayBean.setSign(response2.getData().getSign());
                            wxPayBean.setPrepayid(response2.getData().getPrepayid());
                            wxPayBean.setPartnerid(response2.getData().getPartnerid());
                            wxPayBean.setPackageX(response2.getData().getPackageX());
                            wxPayBean.setNoncestr(response2.getData().getNoncestr());
                            wxPayBean.setAppid(response2.getData().getAppid());
                            PayUtils.getInstance(LevelRechargeActivity.this).toWxPay(wxPayBean, new PayResultListener() {
                                @Override
                                public void onPaySuccess() {
                                    ToastUtils.showToast("支付成功！");
                                    finish();
                                }

                                @Override
                                public void onPayError() {
                                    ToastUtils.showToast("支付失败！");
                                }

                                @Override
                                public void onPayCancel() {
                                    ToastUtils.showToast("支付取消！");
                                }
                            });
                        } else {
                            ToastUtils.showToast(levelPayResponse.getMs());
                        }
                    } else {//支付宝余额支付
                        LevelPayResponse levelPayResponse = JsonUtils.parseByGson(response, LevelPayResponse.class);
                        if (levelPayResponse == null) {
                            return;
                        }
                        if (CallbackCode.SUCCESS.equals(levelPayResponse.getCode())) {
                            if ("3".equals(t)) {//余额
                                ToastUtils.showToast(levelPayResponse.getMs());
                                finish();
                            } else {//支付宝
                                String data = levelPayResponse.getData().replace("&amp;", "&");
                                com.ysxsoft.wdg.util.PayUtils.startAlipay(LevelRechargeActivity.this, mHandler, 0x10, data);//支付宝支付
                            }
                        } else {
                            ToastUtils.showToast(levelPayResponse.getMs());
                        }
                    }
                } else {
                }
            }
        });
    }

    //支付宝支付结果
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0x10:
                    Map<String, String> map = (Map<String, String>) msg.obj;
                    //9000支付成功  8000 正在处理中  4000 订单支付失败  5000重复请求  6001中途取消  6002网络连接出错 6004 支付结果未知  其他其他支付错误
                    if ("9000".equals(map.get("resultStatus"))) {//订单支付成功
                        Toast.makeText(LevelRechargeActivity.this, "支付宝支付成功！", Toast.LENGTH_SHORT).show();
                        finish();
                    } else if ("4000".equals(map.get("resultStatus"))) {//订单支付失败
                        Toast.makeText(LevelRechargeActivity.this, "支付宝支付失败！", Toast.LENGTH_SHORT).show();
                    } else if ("6001".equals(map.get("resultStatus"))) {//订单支付中途取消
                        Toast.makeText(LevelRechargeActivity.this, "支付宝支付取消！", Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    };



    class MyAdapter extends BaseQuickAdapter<LevelResponse.DataBean, BaseViewHolder> {

        public MyAdapter(int layoutResId) {
            super(layoutResId);
        }

        @Override
        protected void convert(BaseViewHolder helper, LevelResponse.DataBean item) {
            helper.setText(R.id.title, item.getName());
            helper.setText(R.id.money, "￥" + item.getService());
            ImageView r = helper.getView(R.id.statusImage);
            if (item.isSelected()) {
                r.setImageResource(R.mipmap.address_selected);
            } else {
                r.setImageResource(R.mipmap.address_default);
            }
        }
    }

    private void getDetail() {

    }
}
